package com.hong.servicecmn.service.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.util.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hong.model.model.cmn.Dict;
import com.hong.model.model.cmn.DictEeVo;
import com.hong.servicecmn.easyexcel.ExcelListener;
import com.hong.servicecmn.mapper.DictMapper;
import com.hong.servicecmn.service.DictService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Service
public class DictServiceImpl extends ServiceImpl<DictMapper, Dict> implements DictService {
    @Autowired
    private DictMapper dictMapper;

    @Cacheable(value = "dict", keyGenerator = "keyGenerator")    //添加缓存
    @Override
    public List<Dict> findChildData(Long id) {
        QueryWrapper<Dict> wrapper = new QueryWrapper<>();
        wrapper.eq("parent_id", id);
        List<Dict> dictList = baseMapper.selectList(wrapper);
        //向list集合的每个dict对象中设置hasChildren
        for (Dict dict : dictList) {
            dict.setHasChildren(this.hasChildren(dict.getId()));
        }
        return dictList;
    }

    @Override
    public void exportDictData(HttpServletResponse response) {
        //设置下载信息
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        String fileName = "dict";
        //设置响应头，以附件的的方式进行下载
        response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
        List<Dict> list = dictMapper.selectList(null);
        List<DictEeVo> newList = new ArrayList<>(list.size());
        for (Dict dict : list) {
            DictEeVo dictEeVo = new DictEeVo();
            BeanUtils.copyProperties(dict, dictEeVo);
            newList.add(dictEeVo);
        }
        try {
            EasyExcel.write(response.getOutputStream(), DictEeVo.class).sheet("dict").doWrite(newList);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    @CacheEvict(value = {"dict","dictName","dictChilds"}, allEntries = true)
    @Override
    public void importDictData(MultipartFile file) {
        try {
            EasyExcel.read(file.getInputStream(), DictEeVo.class, new ExcelListener(dictMapper)).sheet().doRead();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    @Cacheable(value = "dictName")
    @Override
    public String getDictName(String dictCode, String value) {
        if (StringUtils.isEmpty(dictCode)) {
            //根据value直接查询
            Dict dicts = dictMapper.selectByValue(value);
            return dicts.getName();
        } else {
            //根据dictCode和value进行查询,先根据dictCode查询出parentId，再通过parentId和value定位dictName
            String parentId = dictMapper.selectByDictCode(dictCode);
            Dict dicts = dictMapper.findByValueAndParentId(value, parentId);
            return dicts.getName();
        }
    }
    @Cacheable(value = "dictChilds")
    @Override
    public List<Dict> findByDictCode(String dictCode) {
        //根据dictCode获取id
        Dict dict = dictMapper.getDictByDictCode(dictCode);
        //根据id获取子节点
        List<Dict> childData = this.findChildData(dict.getId());
        return childData;
    }

    /**
     * @param id * @return id下是否有子节点
     */
    private boolean hasChildren(Long id) {
        return dictMapper.countDirectChildren(id) > 0;
    }
}
